package br.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.connection.ConnectionFactory;
import br.com.controller.EscolaController;


/**
 * Servlet implementation class EscolaServlet
 */
@WebServlet("/EscolaServlet")
public class EscolaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EscolaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		PrintWriter out = response.getWriter();
		try{
			doInser(request, response);
		}catch (Exception e){
			out.println("ocorreu algum erro");
		}
		
	}
	
	protected void doInser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		request.setCharacterEncoding("UTF-8");        
		response.setCharacterEncoding("UTF-8");
		int inep = Integer.parseInt(request.getParameter("inep"));
		String escola = request.getParameter("escola");
		String end = request.getParameter("end");
		int num = Integer.parseInt(request.getParameter("num"));
		String bairro = request.getParameter("bairro");
		int cid = Integer.parseInt(request.getParameter("cidade"));
		int est = Integer.parseInt(request.getParameter("estado"));
		String pnom = request.getParameter("pnom");
		String pden = request.getParameter("pden");
		String paut = request.getParameter("paut");
		String desc = request.getParameter("desc");
		
		Connection conn = null;

		try {

			conn = new ConnectionFactory().getConnection();
			EscolaController.inserir(conn,inep, escola, end, num, bairro, cid, est, pnom, pden, paut, desc) ;

			out.print("<script type=\"text/javascript\">	alert(\"Cadastrado com sucesso.\");</script>");
			conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (Exception ex) {ex.printStackTrace();}
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {}
		} 
	}

}
